<template>
  <div class="pages invoiceAdd">
    <div class="operationBox tableSearch">
      <el-button type="primary" @click="goBack()" size="mini">返回</el-button>
      <el-button type="primary" @click="submitForm('formdata')" size="mini">保存</el-button>
      <el-button type="primary" @click="sourceList()" size="mini">取来源单</el-button>
      <el-button type="primary" @click="deleted()" size="mini">批量删除商品</el-button>
    </div>
    <!-- 表单开始 -->
    <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="企业客户：" prop="brand">
            <el-input placeholder="请选择企业客户" v-model="formdata.brand" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出库仓库：" prop="warehouseId">
            <el-select v-model="formdata.warehouseId" @change="getwarehouseName">
              <el-option v-for="(item,index) in warehouseArray" :key="index" :label="item.repositoryName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货状态：">
            <el-input v-model="saleReceivingsStatusArr[formdata.status]" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出库日期：" prop="receiveDate">
            <el-date-picker v-model="formdata.receiveDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择交货日期"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编号：">
            <el-input v-model="formdata.danjuCode" disabled placeholder="单据编号自动生成"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期：" prop="orderDate">
            <el-date-picker v-model="formdata.orderDate" disabled format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货人：" prop="consignee">
            <el-select v-model="contactData.id" @change="selectContact">
              <el-option v-for="(item, index) in contactList" :key="index" :label="item.consignee" :value="item.id"></el-option>
            </el-select>
            <el-button type="text" @click="editContact()" size="mini">修改</el-button>
            <el-button type="text" @click="delContact()" size="mini">删除</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="">
            <el-button type="primary" @click="clickAddContact()" size="mini">添加收货人</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="手机号码：">
            <span>{{contactData.linkman}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="座机电话：">
            <span>{{contactData.fixPhone}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地址：">
            <span>{{contactData.detailAddress}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="物流单号：">
            <el-input v-model="formdata.logisticsCode" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表格 -->
    <div class="tableMain">
      <el-table :data="tableData" stripe style="width: 100%" @selection-change="changeFunDelete_good">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="#" width="55"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="goodsName" label="商品" align="center" width="200"></el-table-column>
        <!-- 销售订单紧带入 -->
        <el-table-column prop="goodsBatchNumber" label="商品批次" align="center" width="150">
          <template slot-scope="scope" >
            <el-select   v-if="scope.row.isBatch === '1'" v-show="scope.row.showBatch" @change="goodsBatchNumberChange" @focus="batchSelect(scope.row, scope.$index)"  v-model="scope.row.goodsBatchNumber" size="mini">
              <el-option v-for="item in scope.row.goodsBatchNumberList" :key="item.index" :value="item.goodsBatchNumber"> </el-option>
            </el-select>
            <span v-if="scope.row.isBatch === '1'" v-show="!scope.row.showBatch">{{scope.row.goodsBatchNumber}}</span>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
            <!-- <input v-else class="commonInput" v-model="scope.row.goodsBatchNumber" size="mini" type="text" value="1" min="1" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else if(this.value){this.value=parseInt(this.value.replace(/\D/g,''))}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}"> -->
          </template>
          <!-- <template slot-scope="scope" >
            <span v-if="scope.row.isBatch === '1'">{{scope.row.goodsBatchNumber}}</span>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          </template>  -->
        </el-table-column>
        <!-- 集团订单新加功能5/31 -->
        <el-table-column prop="dateInProduced" label="生产日期" align="center" width="100">
          <template slot-scope="scope" >
            <span v-if="scope.row.isBatch === '1'">{{scope.row.dateInProduced}}</span>
            <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsSpec" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
              <span>{{item.paramName}} :</span><span>{{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
        <el-table-column prop="goodsPrice" label="销售价" align="center"></el-table-column>
        <el-table-column prop="goodsQuantity" label="库存数量" align="center"></el-table-column>
        <el-table-column prop="goodsNum" label="数量" align="center" width="150">
          <template slot-scope="scope">
            <div class="el-input el-input--mini">
              <input class="el-input__inner" v-model="scope.row.sendNum" size="mini" type="text" style="width:100px" value="1" min="1" maxlength="8" @input="watchInput(scope.row.goodsQuantity, scope.row.sendNum, scope.$index, scope.row.isBatch)" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="goodsAmount" label="总价" align="center">
          <template slot-scope="scope">
            <span>{{(Number(scope.row.goodsPrice)*Number(scope.row.sendNum)).toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="handleCancel(scope.$index)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="th-right">
      <el-form :model="formdata" :rules="rules" label-width="120px" size="mini">
        <el-row>
          <el-col :span="8">&nbsp;</el-col>
          <el-col :span="6">
            <el-form-item label="操作员：">
              <el-input v-model="formdata.creator" disabled></el-input>
            </el-form-item>
            <el-form-item label="备注：">
              <el-input v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="总计：">
              <el-input v-model="formdataTotal" disabled></el-input>
            </el-form-item>
            <el-form-item label="应收总计：">
              <el-input v-model="formdataAllTotal" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 取来源单窗口 -->
    <el-dialog title="销售订单" class="addshopname" :visible.sync="dialogTableVisible_cai" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
      <i class="el-icon-close icon" @click="dialogTableVisible_cai=false"></i>
      <div class="operationBox tableSearch">
        <el-button size="mini" type="primary" @click="handleSeleceSource()">选择</el-button>
        <el-button size="mini" @click="dialogTableVisible_cai=false">取消</el-button>
      </div>
      <div style="margin-bottom:10px;margin-top:10px;">
        <el-input size="mini" placeholder="请输入单据号" v-model="selectData.saleCode"></el-input>
        <el-button size="mini" type="primary" @click="sourceSerch">查询</el-button>
      </div>
      <el-table :data="caiArray" stripe border tooltip-effect="dark" highlight-current-row @current-change="changeSource">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="saleCode" label="单据编号" align="center"></el-table-column>
        <el-table-column prop="orderDate" :formatter="tim" label="日期" align="center"></el-table-column>
        <el-table-column prop="shopName" label="客户" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="getSourcePageData" :func="getGoodsSaleListPage"></page-unit>
    </el-dialog>
    <!-- 联系人弹窗 -->
    <el-dialog title="联系人" class="addshopname" :visible.sync="dialogContact" :closeOnClickModal='false' :closeOnPressEscape='false' width="35%">
      <i class="el-icon-close icon" @click="dialogContact=false"></i>
      <el-form :model="contactDialogForm" :rules="rulesContact" ref="contactDialogForm" size="mini" label-width="100px">
        <el-form-item label="收货人：" prop="consignee">
          <el-input v-model="contactDialogForm.consignee" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：" prop="linkman">
          <el-input v-model="contactDialogForm.linkman" maxlength="11" @keyup.native='replace(contactDialogForm.linkman, contactDialogForm, "linkman")'></el-input>
        </el-form-item>
        <el-form-item label="座机号码：">
          <el-input v-model="contactDialogForm.fixPhone" maxlength="12" @keyup.native='replace(contactDialogForm.fixPhone, contactDialogForm, "fixPhone")'></el-input>
        </el-form-item>
        <el-form-item label="地址：" prop="area">
          <v-distpicker @selected="onSelected" :province="contactDialogForm.province" :city="contactDialogForm.city" :area="contactDialogForm.area"></v-distpicker>
        </el-form-item>
        <el-form-item label="" prop="address">
          <el-input v-model="contactDialogForm.address" placeholder="详细地址(必填)" maxlength="200"></el-input>
        </el-form-item>
        <el-form-item label="设为默认地址">
          <el-switch v-model="contactDialogForm.isDefault" inactive-color="red" active-value="0" inactive-value="1"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSaveContact('contactDialogForm')">保存</el-button>
          <el-button @click="dialogContact=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import utils from "@/util/state";
import u from "@/util";
import VDistpicker from "v-distpicker";
import SdInput from "components/SdInput";
import pageUnit from "components/Page";
import {
  getGoodsSaleListPage,
  getRepositoryListPage,
  addRepertoryOutBound,
  selectByWarIdAndSaleId,
  getDeliveryAddressList,
  updateDeliveryAddress,
  saveDeliveryAddress
} from "@/api";
export default {
  components: { SdInput, pageUnit, VDistpicker },
  data () {
    return {
      sourceId: "",  // 选择的来源单id
      dialogTableVisible_cai: false,  // 弹窗的显示隐藏
      caiArray: [],  // 取来源单数组
      selectionSource: {},  // 选中一条的值
      getSourcePageData: {
        pageSize: 20, // 分页开始
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      selectData: {
        saleCode: ''  // 搜索单据号的初始化
      },
      warehouseArray: [],  // 仓库数组
      saleReceivingsStatusArr:utils.saleReceivingsStatusArr,//订单状态
      tableData: [], //表格数据
      formdata: {
        warehouseId: "",  // 选择的出库仓库id
        goodsBatchNumber: "",
        supplierId: "",
        status: 0,
        shouhuoStatus: 0,
        fukuanStatus: 0,
        supplierName: "",
        purchaseStatus: "",
        receiveDate: "",
        orderDate: "",
        danjuCode: '',
        purchaseinCode: "",
        remark: "",
        purchaseAmount: 0,
        taxAmount: 0,
        amount: 0,
        brand: "", //企业客户
        logisticsCode: '',  // 物流单号
        consignee: ''
      }, //表单数据
      contactData: {
        id: '',  // 选中的收货人Id
        consignee: '',  // 收货人
        fixPhone: '',  // 收货人座机号
        linkman: '',  // 收货人手机
        countries: '中国',
        province: '',  // 收货人省
        city: '',  // 收货人市
        area: '',  // 收货人区
        address: '',  // 收货人地址
        detailAddress: '',  // 收货人详细地址
        isDefault: '1',  // 是否默认
      },
      contactDialogForm: {
        id: '',
        consignee: '',
        fixPhone: '',
        linkman: '',
        countries: '中国',
        province: '',
        city: '',
        area: '',
        address: '',
        isDefault: '1'
      },  // 联系人弹窗表单
      dialogContact: false,  // 联系人弹窗
      contactList: [],  // 收货人数组
      //表单数据验证
      buildOneself: true,
      rules: {
        brand: [{required: true,message: "请先选择客户",trigger: "blur"}],
        receiveDate: [{ required: true, message: "请选择交货时间", trigger: "blur" }],
        consignee: [{ required: true, message: "请选择收货人", trigger: "blur" }],
      },
      deleteList: [], //批量删除商品数组
      paymentMethod: ["线下付款", "线上付款", "预付款支付"], // 支付方式数组
      rulesContact: {
        consignee: [{ required: true, message: "请输入收货人", trigger: "blur" }],
        linkman: [
          { required: true, message: "请输入手机号码", trigger: "blur"  },
          { validator: u.validMobilePhoneCallback, trigger: 'blur' }
        ],
        area: [{ required: true, message: "请选择地址", trigger: "blur"  }],
        address: [{ required: true, message: "请输入地址信息", trigger: "blur" }]
      },
      batchSelectGood: '',  // 商品批次多选时定位选择的商品
      batchIndex: '',  // 商品批次多选时定位位置
    };
  },
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      companyName: state => state.companyName,
      userId: state=> state.userId
    }),
    // 总计的算法
    formdataTotal: function () {
      let totalPrice = 0;
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsAmount =
          this.tableData[i].goodsPrice * this.tableData[i].sendNum;
        totalPrice += this.tableData[i].goodsPrice * this.tableData[i].sendNum;
      }
      this.formdata.purchaseAmount = totalPrice.toFixed(2);
      return isNaN(totalPrice) ? 0 : totalPrice.toFixed(2);
    },
    // 应付总计的算法
    formdataAllTotal: function () {
      let totalPrice = 0;
      totalPrice = Number(this.formdataTotal)
      if (totalPrice == NaN || totalPrice == 0) {
        this.formdata.amount = 0;
        return totalPrice;
      } else {
        this.formdata.amount = totalPrice.toFixed(2);
        return totalPrice.toFixed(2);
      }
    },
  },
  mounted () {
    this.init();  // 初始化数据
    this.getRepositoryListPage();  // 获取出库仓库数组
  },
  methods: {
    // 监测商品输入数量不能大于库存数量
    watchInput(goodsQuantity, sendNum, index, isBatch) {
      if(isBatch === '1') {
        if(goodsQuantity !== undefined) {
          if(Number(sendNum) > Number(goodsQuantity)) {
            this.$message.error('输入数量不能大于库存数量！')
            this.tableData[index].sendNum = goodsQuantity
            return
          }
        } 
      }
    },
    // 时间戳转换
    tim (row) {
      return u.foryear(row.orderDate);
    },
    // 初始化单据日期和操作员
    init () {
      this.formdata.orderDate = u.getNowFormatDate();
      this.formdata.creator = this.companyName;
    },
    replace(value,obj,key) {
      let res = ''
      switch (key) {
        case 'linkman':
          res = u.replaceNumber(value);
          break;
        case "fixPhone":
          res = u.replaceFixPhone(value);
          break;
        default: 
          break;
      }
      this.$set(obj,key,res);
    },
    // 获取出库仓库数组
    getRepositoryListPage () {
      let data = {
        shopId: this.merchantId,
        nameCode: '',
        openingInventoryState: 1,
        status: "0"
      };
      getRepositoryListPage(data).then(res => {
        this.warehouseArray = res.data.list;
      });
    },
    // 选择出库仓库
    getwarehouseName (val) {
      this.tableData = [];
      this.warehouseArray.forEach(ele => {
        if (ele.id == val) {
          if (ele.openingInventoryState == 0) {
            this.$message.error('该仓库未录入期初库存')
            this.formdata.warehouseId = "";
          }
        }
      });
    },
    // 点击取来源单按钮
    sourceList () {
      this.getGoodsSaleListPage(this.getSourcePageData.pageSize, 1);
    },
    // 来源单列表弹窗接口
    getGoodsSaleListPage (pageSize, pageNum) {
      if(this.formdata.warehouseId !== '') {  // 判断先选择出库仓库
        getGoodsSaleListPage({
          pageSize: pageSize,
          pageNum: pageNum,
          saleCode: this.selectData.saleCode,
          statusFlow: 3,
          supplierId: this.merchantId
        }).then(res => {
          this.caiArray = res.data.list;
          this.getSourcePageData.totalItems = res.data.pageTotal;
        });
        this.dialogTableVisible_cai = true;
      } else {
        this.$message.error("请选择出库仓库")
      }
    },
    // 确定选择来源单
    handleSeleceSource () {
      this.sourceId = this.selectionSource.id;
      this.formdata.brand = this.selectionSource.shopName;
      this.formdata.supplierId = this.selectionSource.shopId;
      this.formdata.supplierName = this.selectionSource.shopName;
      this.formdata.logisticsCode = ''
      let data = {
        saleId: this.sourceId,
        repositoryId: this.formdata.warehouseId,
        sendNum:"1"
      };
      selectByWarIdAndSaleId(data).then(res => {
        this.tableData = res.data.goodsList
        this.tableData.forEach(item => {
          // if(item.isBatch === '0') {
          //   item.goodsQuantity = item.repositoryGoodsList[0].goodsQuantity
          //   item.dateInProduced = item.repositoryGoodsList[0].dateInProduced
          // }
          if(item.isBatch==="1"){
             if(item.goodsBatchNumber==""||item.goodsBatchNumber==undefined){
               item.showBatch=true
             }else{
               item.showBatch=false
             }
          }
        })
        this.dialogTableVisible_cai = false;
        this.getContactList()  // 获取该企业客户的收货人列表
      });
    },
    // 来源单列表切换选择
    changeSource (val) {
      if (val) {
        this.selectionSource = val;
      } else {
        this.selectionSource = [];
      }
    },
    // 来源单弹窗查询
    sourceSerch () {
      this.getSourcePageData.currentPage=1;
      this.getGoodsSaleListPage(this.getSourcePageData.pageSize, this.getSourcePageData.currentPage);
    },
    goodsBatchNumberChange(val){
      let goodsBatchNumber = val
      let goodsId = this.batchSelectGood.goodsId
      let resData = this.batchSelectGood.goodsBatchNumberList.filter(item => {
        return item.goodsBatchNumber === goodsBatchNumber
      })
      this.batchSelectGood.goodsQuantity=resData[0].goodsQuantity
      this.batchSelectGood.dateInProduced=resData[0].dateInProduced
      let i = this.batchIndex
      this.tableData[i] = this.batchSelectGood
    },
    batchSelect(good, index) {
      this.batchSelectGood = good
      this.batchIndex = index
    },
    // 点击返回按钮
    goBack () {
      history.back();
    },
    // 单条删除商品
    handleCancel (index) {
      this.tableData.splice(index, 1);
    },
    // 批量删除多选
    changeFunDelete_good (val) {
      this.deleteList = val;
    },
    // 批量删除商品
    deleted () {
      let self = this;
      this.tableData = this.tableData.filter(function (item) {
        return self.deleteList.indexOf(item) == -1;
      });
    },
    // 点击修改收货人
    editContact() {
      if(this.contactData.id !== '') {
        let resData = this.contactList.filter(item => {
          return item.id === this.contactData.id
        })
        Object.keys(resData[0]).forEach(key => {
          this.contactDialogForm[key] = resData[0][key]
        })
        this.$set(this.contactDialogForm, 'isDefault', resData[0].isDefault.toString())
        this.dialogContact = true
      }
    },
    // 点击删除收货人
    delContact() {
      if(this.contactData.id !== '') {
        this.$confirm("确定要删除当前收货人吗?", "提示", {
          center: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false,
          closeOnPressEscape: false
        }).then(() => {
          let data = {
            id: this.contactData.id,
            dl: 1
          };
          updateDeliveryAddress(data).then(res => {
            if(res.code == 200) {
              this.$message.success(res.msg)
              this.getContactList()
            }
          });
        }).catch(() => {})
      }
    },
    // 点击添加收货人
    clickAddContact() {
      if(this.sourceId) {
         Object.keys(this.contactDialogForm).forEach(key => {
          this.contactDialogForm[key] = ''
        })
        this.$set(this.contactDialogForm, 'isDefault', '1')
        this.dialogContact = true
      } else {
        this.$message.error('请先取来源单！')
      }
    },
    // 获取收货人列表
    getContactList() {
      getDeliveryAddressList({
        shopId: this.merchantId,
        customerId: this.formdata.supplierId
      }).then(res => {
        if(res.code == 200) {
          this.contactList = res.data.list
          this.contactList.forEach(item => {
            item.detailAddress = item.province + item.city + item.area + item.address
          })
          if(this.contactList.length !== 0) {
            let defaultCon = this.contactList.filter(item => {
              return Number(item.isDefault) === 0
            })
            if(defaultCon.length === 1) {  // 选择默认地址
              Object.keys(defaultCon[0]).forEach(key => {
                this.contactData[key] = defaultCon[0][key]
              })
              this.formdata.consignee = this.contactData.consignee
            } else {  // 无默认地址，取最新一条
              let len = this.contactList.length
              Object.keys(this.contactList[len-1]).forEach(key => {
                this.contactData[key] = this.contactList[len-1][key]
              })
              this.formdata.consignee = this.contactData.consignee
            }
          } else {
            // 可能是删除完数据，所以要清除缓存数据
            Object.keys(this.contactData).forEach(key => {
              this.contactData[key] = ''
            })
            this.contactData.isDefault = '1'
          }
        }
      })
    },
    // 选择收货人
    selectContact(val) {
      if(val) {
        let data = this.contactList.filter(item => {
          return item.id === val
        })
        Object.keys(data[0]).forEach(key => {
           this.contactData[key] = data[0][key]
        })
        this.formdata.consignee = this.contactData.consignee
      }
    },
    // 地址联动选择
    onSelected(val) {
      this.contactDialogForm.province = val.province.value;
      this.contactDialogForm.city = val.city.value;
      this.contactDialogForm.area = val.area.value;
    },
    // 收货人弹窗点击确定
    handleSaveContact(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(this.contactDialogForm.id !== '') { // 修改
            updateDeliveryAddress({
              id: this.contactData.id,
              consignee: this.contactDialogForm.consignee,
              linkman: this.contactDialogForm.linkman,
              fixPhone: this.contactDialogForm.fixPhone,
              countries: this.contactDialogForm.countries,
              province: this.contactDialogForm.province,
              city: this.contactDialogForm.city,
              area: this.contactDialogForm.area,
              address: this.contactDialogForm.address,
              isDefault: this.contactDialogForm.isDefault,
              dl: 0
            }).then(res => {
              if(res.code == 200) {
                this.getContactList()
                this.dialogContact = false
              }
            })
          } else {
            if(this.contactList.length === 50) {
              this.$message.error('收货人最多50条！')
              return false;
            }
            saveDeliveryAddress({
              shopId: this.merchantId,
              customerId: this.formdata.supplierId,
              consignee: this.contactDialogForm.consignee,
              linkman: this.contactDialogForm.linkman,
              fixPhone: this.contactDialogForm.fixPhone,
              countries: this.contactDialogForm.countries,
              province: this.contactDialogForm.province,
              city: this.contactDialogForm.city,
              area: this.contactDialogForm.area,
              address: this.contactDialogForm.address,
              isDefault: this.contactDialogForm.isDefault
            }).then(res => {
              if(res.code == 200) {
                this.getContactList()
                this.dialogContact = false
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 保存按钮
    submitForm (formName) {
      if(this.contactData.id !== '') {
        this.formdata.consignee = this.contactData.consignee
      } else {
        this.$message.error('请先选择收货人')
        return false
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.sourceId === "") {
            for (let i = 0; i < this.tableData.length; i++) {
              this.tableData[i].goodsName = this.tableData[i].name;
              this.tableData[i].goodsNum = this.tableData[i].sendNum;
              if (this.tableData[i].sendNum <= 0) {
                this.$message.error('数量不能小于等于0')
                return false;
              }
            }
          } else {
            for (let i = 0; i < this.tableData.length; i++) {
              this.tableData[i].goodsNum = this.tableData[i].sendNum;
              if (this.tableData[i].sendNum <= 0) {
                this.$message.error("数量不能小于等于0")
                return false;
              }
            }
          }
          if (this.tableData.length == 0) {
            this.$message.error("商品不能为空")
            return false;
          }
          if(this.contactData.id !== '') {
            this.formdata.consignee = this.contactData.consignee
          } else {
            this.$message.error('请先选择收货人')
            return false
          }
          this.tableData.forEach(i => {
            delete i.createTime;
            delete i.updateTime;
            i.goodsAmount = i.goodsPrice * i.goodsNum;
            i.goodsDetailId=i.id
          });
          let repName = "";
          this.warehouseArray.forEach(ele => {
            if (ele.id == this.formdata.warehouseId) {
              repName = ele.repositoryName;
            }
          });
          addRepertoryOutBound({
            shopId: this.merchantId,
            shopName: this.companyName,
            warehouseId: this.formdata.warehouseId,
            remark: this.formdata.remark,
            warehouseName: repName,
            creater: this.userId,
            goodsList: JSON.stringify(this.tableData),
            orderSaleId: this.sourceId,
            outType: 1,
            customerId: this.formdata.supplierId,
            customerName: this.formdata.supplierName,
            consignee: this.contactData.consignee,
            linkman: this.contactData.linkman,
            fixPhone: this.contactData.fixPhone,
            address: this.contactData.address,
            countries: '中国',
            province: this.contactData.province,
            city: this.contactData.city,
            area: this.contactData.area,
            deliveryAddressList: JSON.stringify(this.contactList),
            logisticsCode: this.formdata.logisticsCode
          }).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              u.routerTo("/order-center/sale-management/sale-invoiceList");
            }
          });
        } else {
          return false;
        }
      });
    },
  }
};
</script>
<style>
.distpicker-address-wrapper select {
  height: 32px;
  font-size: 13px;
  padding: 0 .75rem;
}
</style>
<style scoped>
.th-right {
  margin-top: 20px;
}
</style>
